package com.crm.dataReceive.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.crm.channel.domain.BaseChannel;
import com.crm.channel.service.IBaseChannelService;
import com.crm.custinfo.domain.CustBlackList;
import com.crm.custinfo.domain.CustCommentRecord;
import com.crm.custinfo.domain.CustInfo;
import com.crm.custinfo.domain.HitPackage;
import com.crm.custinfo.service.ICustBlackListService;
import com.crm.custinfo.service.ICustCommentRecordService;
import com.crm.custinfo.service.ICustInfoService;
import com.crm.custinfo.service.IHitPackageService;
import com.crm.dataReceive.domain.Customer;
import com.crm.suborgConfig.service.IBaseSuborgConfigService;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.constant.ConfigConstant;
import com.ruoyi.common.constant.TypeConstant;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.*;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;

/**
 * 功能说明: 分发系统分发数据接收API<br>
 * 开发人员: @author Mr.Wen<br>
 *
 * @date 2023-12-28
 */
@RestController
@RequestMapping("/dataCenter")
public class DataReceiveController extends BaseController {
    public static final org.slf4j.Logger logger = LoggerFactory.getLogger("custApiLog");
    @Autowired
    private ISysConfigService baseSysConfigService;
    @Autowired
    private ICustInfoService custInfoService;
    @Autowired
    private ICustBlackListService custBlackListService;
    @Autowired
    private ICustCommentRecordService custCommentRecordService;

    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private IBaseChannelService iBaseChannelService;
    @Autowired
    private IBaseSuborgConfigService iBaseSuborgConfigService;
    @Autowired
    private IHitPackageService iHitPackageService;
    private int code;// code：0 推送成功 code：-1 推送失败
    private String msg; //
    private List<Map<String, Object>> list; // 排重包list

    public List<Map<String, Object>> getList() {
        return list;
    }

    public void setList(List<Map<String, Object>> list) {
        this.list = list;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Map<String, Object> getResult() {
        Map<String, Object> result = new HashMap<>();
        result.put("code", getCode());
        result.put("msg", getMsg());
        result.put("list", getList());
        return result;
    }

    /**
     * 期初数据整理，下次版本剔除此接口
     *
     * @return
     */
    @Anonymous
    @PostMapping("/test")
    public String test() {

        CustInfo custInfo = new CustInfo();
        custInfo.setRepeatFlag("0");
        List<CustInfo> list = custInfoService.selectCustInfoList(custInfo);
        for (CustInfo item : list) {
            HitPackage sel = new HitPackage();
            sel.setMobileMd5(item.getMd5val());
            List<HitPackage> getlsit = iHitPackageService.selectHitPackageList(sel);
            if (getlsit.isEmpty()) {
                AjaxResult s = custInfoService.decryptMobile(item);
                String phone = (String) s.getOrDefault("msg", "");
                int ss = (int) s.getOrDefault("code", "");
                if (ss != 500) {
                    HitPackage insHitPackage = new HitPackage();
                    insHitPackage.setCity(item.getCity());
                    insHitPackage.setMobileMd5(item.getMd5val());
                    insHitPackage.setMobilePrefix8Md5(Md5Encrypt.md5(phone.substring(0, 8)));
                    insHitPackage.setMobileSha256(Md5Encrypt.sha256(phone));
                    insHitPackage.setApplyTime(item.getApplyTime());
                    iHitPackageService.insertHitPackage(insHitPackage);
                }
            }
        }
        return "";
    }

    /**
     * 根据prefix8查询撞库包
     *
     * @return
     */
    @Anonymous
    @PostMapping("/getHitPackage4prefix8/tenant/{tenantId}")
    public String getHitPackage4prefix8() {
        String requestBoday = getRequestBoday();
        JSONObject json = JSONObject.parseObject(requestBoday);
        String prefix8 = json.getString("prefix8");
        HitPackage sel = new HitPackage();
        sel.setMobilePrefix8Md5(prefix8);
        List<HitPackage> getlsit = iHitPackageService.selectHitPackageList(sel);
        return JSON.toJSONString(getlsit);
    }
    @Anonymous
    @PostMapping("/getHitPackage4mobilemd5/tenant/{tenantId}")
    public String getHitPackage4mobilemd5() {
        String requestBoday = getRequestBoday();
        JSONObject json = JSONObject.parseObject(requestBoday);
        String mobileMd5 = json.getString("mobileMd5");
        HitPackage sel = new HitPackage();
        sel.setMobileMd5(mobileMd5);
        List<HitPackage> getlsit = iHitPackageService.selectHitPackageList(sel);
        return JSON.toJSONString(getlsit);
    }
    /**
     * 添加客户
     *
     * @return
     */
    @Anonymous
    @PostMapping("/addCust/tenant/{tenantId}")
    public String addCust() {
        return apply();
    }

    public String apply() {
        try {
            String requestBoday = getRequestBoday();
            JSONObject json = JSONObject.parseObject(requestBoday);
            if (json == null) {
                setCode(-1);
                setMsg("请求包数据为空");
                return JSON.toJSONString(getResult());
            }
            logger.info("分发数据接收API请求参数原文：{}", json);
            String data = json.getString("data");// 加密结果
            // 数据解密key
            String key = baseSysConfigService.getItemValueByItemKey(ConfigConstant.DATA_CENTER_AES_KEY);
            // 数据解密
            String dataStr = AesUtils.decrypt(data, key);
            if (StringUtils.isBlank(dataStr)) {
                setCode(-1);
                setMsg("数据解密异常");
                return JSON.toJSONString(getResult());
            }
            JSONObject req = JSONObject.parseObject(dataStr);
            Customer customer = JSON.toJavaObject(req, Customer.class);
            logger.info("线索接收API请求参数：{}", customer.toString());
            // 是否作为重复数据入库
            int isRepeat = req.getIntValue("isRepeat");
            int count = custInfoService.countByMd5(Md5Encrypt.md5(customer.getMobile()));
            if (count > 0 && isRepeat == 0) {
                setCode(-1);
                setMsg("撞库未通过");
                return JSON.toJSONString(getResult());
            }
            if (count == 0 && isRepeat == 1) {
                // 如果显示是重复入库但实际库中没有，也不算重复标识
                isRepeat = 0;
            }
            CustInfo custInfo = new CustInfo();
            ObjectUtil.copyProperties(customer, custInfo);
            if (custInfo.getApplyTime() == null) {
                custInfo.setApplyTime(new Date());
            }
            custInfo.setMd5val(Md5Encrypt.md5(custInfo.getMobile()));
            // 分发系统唯一id
            custInfo.setDistributeId(Long.parseLong(customer.getCustomerId().toString()));
            // 分发系统分过来的时间
            custInfo.setDistributeTime(new Date());
            logger.info("线索接收API请求转换：{}", custInfo.toString());
            // 客户申请信息前置检查
            Map<String, Object> checkResult = custInfoService.checkCustInfo(custInfo, logger);
            if (MapUtils.getIntValue(checkResult, "errorNo", -1) != 0) {
                setCode(-1);
                setMsg(MapUtils.getString(checkResult, "errorInfo", ""));
                return JSON.toJSONString(getResult());
            }
            logger.info("线索接收API：重复标识{}", isRepeat);
            if (isRepeat == 1) {
                CustInfo inParams = new CustInfo();
                inParams.setMd5val(custInfo.getMd5val());
                List<CustInfo> custInfos = custInfoService.selectCustInfoList(inParams);
                CustInfo lastCust = custInfos.get(0);
                // 设置重复标识
                custInfo.setRepeatFlag(lastCust.getEmpId() == null ? "1" : "2");
                custInfo.setLastRemarkTime(new Date());
                if (lastCust.getEmpId() != null) {
                    SysUser lastUser = iSysUserService.selectUserById(lastCust.getEmpId());
                    if (TypeConstant.FLAG_NO.equals(lastUser.getDelFlag())) {
                        // 原客户经理有效则分给原客户经理
                        if (custInfoService.dealCustReplay(custInfo, lastCust.getId(), lastUser, logger)) {
                            setCode(0);
                            setMsg("线索接收成功");
                            return JSON.toJSONString(getResult());
                        }
                    }
                }
            } else {
                custInfo.setRepeatFlag("0");
            }

            // 随机分配
            Long[] orgIds = custInfoService.getOrgIdsByCity(custInfo.getCity());
            boolean isSucceed = custInfoService.dealCustRandomly(custInfo, orgIds, true, false, logger);
            if (isSucceed) {
                setCode(0);
                setMsg("线索接收成功");
                if (StringUtils.isNotBlank(custInfo.getRemark())) {
                    // 自动生成一条备注
                    CustCommentRecord record = new CustCommentRecord();
                    record.setCustId(custInfo.getId());
                    record.setEmpId(null);
                    record.setEmpName("系统自动备注");
                    record.setRemark(custInfo.getRemark());
                    record.setType(1L);
                    record.setType2(1L);
                    record.setCreateTime(new Date());

                    custCommentRecordService.insertCustCommentRecord(record);
                }
            } else {
                setCode(-1);
                setMsg("线索接收API请求申请异常");
            }
            setList(null);
        } catch (Exception e) {
            logger.info("线索接收API请求异常：", e.getMessage());
            setCode(-1);
            setMsg("api请求异常：" + e.getMessage());
        } finally {
            logger.info("线索接收API请求结果：code={}，msg = {}", code, msg);
        }
        return JSON.toJSONString(getResult());
    }

    /**
     * 星级状态查询
     *
     * @return
     */
    @Anonymous
    @PostMapping("/syncStarStatus/tenant/{tenantId}")
    public String syncStarStatus() {
        try {
            long begin = System.currentTimeMillis();
            String requestBoday = getRequestBoday();
            JSONObject json = JSONObject.parseObject(requestBoday);
            if (json == null) {
                setCode(-1);
                setMsg("请求包数据为空");
                return JSON.toJSONString(getResult());
            }
            // 验证身份能解密就放行
            String token = json.getString("token");
            if (StringUtils.isBlank(token)) {
                setCode(-1);
                setMsg("无权限访问");
                return JSON.toJSONString(getResult());
            }
            String realVal = AesUtils.decrypt(token, baseSysConfigService.getItemValueByItemKey(ConfigConstant.DATA_CENTER_AES_KEY));
            if (StringUtils.isBlank(realVal)) {
                setCode(-1);
                setMsg("无权限访问");
                return JSON.toJSONString(getResult());
            }
            // 开始时间
            String start_time = StringUtils.defaultIfBlank(json.getString("start_time"), "");
            if (StringUtils.isBlank(start_time)) {
                setCode(-1);
                setMsg("查询开始时间为空");
                return JSON.toJSONString(getResult());
            }
            setCode(0);
            Map<String, Object> inParams = new HashMap<String, Object>();
            inParams.put("start_time", start_time);

            setList(custInfoService.getStarStatusDetail(inParams));
            long end = System.currentTimeMillis();
            logger.info("星级状态查询{}，结果集数量：{}, 耗时{}ms", start_time, list.size(), (end - begin));
        } catch (Exception e) {
            logger.error("星级状态查询异常", e);
            setCode(-1);
            setMsg("星级状态查询异常");
            return JSON.toJSONString(getResult());
        }
        return JSON.toJSONString(getResult());
    }

    /**
     * 黑名单查询
     *
     * @return
     */

    @Anonymous
    @PostMapping("/syncBlacklist/tenant/{tenantId}")
    public String syncBlacklist() {
        try {
            list = new ArrayList<>();
            long begin = System.currentTimeMillis();
            String requestBoday = getRequestBoday();
            JSONObject json = JSONObject.parseObject(requestBoday);
            if (json == null) {
                setCode(-1);
                setMsg("请求包数据为空");
                return JSON.toJSONString(getResult());
            }
            // 验证身份能解密就放行
            String token = json.getString("token");
            if (StringUtils.isBlank(token)) {
                setCode(-1);
                setMsg("无权限访问");
                return JSON.toJSONString(getResult());
            }
            String realVal = AesUtils.decrypt(token, baseSysConfigService.getItemValueByItemKey(ConfigConstant.DATA_CENTER_AES_KEY));
            if (StringUtils.isBlank(realVal)) {
                setCode(-1);
                setMsg("无权限访问");
                return JSON.toJSONString(getResult());
            }
            // 开始时间
            String start_time = StringUtils.defaultIfBlank(json.getString("start_time"), "");
            if (StringUtils.isBlank(start_time)) {
                setCode(-1);
                msg = "查询开始时间为空";
                return JSON.toJSONString(getResult());
            }
            CustBlackList custBlackList = new CustBlackList();
            Map<String, Object> params = new HashMap<>();
            params.put("startTime", start_time);

            custBlackList.setParams(params);

            List<CustBlackList> blackLists = custBlackListService.selectCustBlackListList(custBlackList);


            for (CustBlackList blackList : blackLists) {
                Map<String, Object> map = new HashMap<>();
                map.put("md5", Md5Encrypt.md5(blackList.getMobile()));
                map.put("dens", SecurityUtil.getMobile(blackList.getMobile()));
                list.add(map);
            }
            setCode(0);
            setMsg("success");
            long end = System.currentTimeMillis();
            logger.info("黑名单查询{}，结果集数量：{}, 耗时{}ms", start_time, list.size(), (end - begin));
        } catch (Exception e) {
            logger.error("黑名单查询异常", e);
            setCode(-1);
            setMsg("黑名单查询异常");
            return JSON.toJSONString(getResult());
        }
        return JSON.toJSONString(getResult());
    }

    /**
     * 渠道同步
     *
     * @return
     */
    @Anonymous
    @PostMapping("/syncChannel/tenant/{tenantId}")
    public String syncChannel() {
        try {
            list = new ArrayList<>();
            String requestBoday = getRequestBoday();
            JSONObject json = JSONObject.parseObject(requestBoday);
            if (json == null) {
                setCode(-1);
                setMsg("请求包数据为空");
                return JSON.toJSONString(getResult());
            }
            // 验证身份能解密就放行
            String token = json.getString("token");
            if (StringUtils.isBlank(token)) {
                setCode(-1);
                setMsg("无权限访问");
                return JSON.toJSONString(getResult());
            }
            String realVal = AesUtils.decrypt(token, baseSysConfigService.getItemValueByItemKey(ConfigConstant.DATA_CENTER_AES_KEY));
            if (StringUtils.isBlank(realVal)) {
                setCode(-1);
                setMsg("无权限访问");
                return JSON.toJSONString(getResult());
            }
            String channel_source = json.getString("channel_source");
            String channel_name = json.getString("channel_name");
            if (StringUtils.isBlank(channel_source) || StringUtils.isBlank(channel_name)) {
                setCode(-1);
                setMsg("参数缺失");
                return JSON.toJSONString(getResult());
            }
            BaseChannel baseChannel = iBaseChannelService.getChannelInfo(channel_source);
            if (baseChannel == null) {
                // 渠道不存在则添加
                List<String> citys = iBaseSuborgConfigService.getAllCitys();
                for (String city : citys) {
                    baseChannel = new BaseChannel();
                    baseChannel.setChannelSource(channel_source);
                    baseChannel.setChannelName(channel_name);
                    baseChannel.setRejectDays(360L);
                    baseChannel.setAutoFindDays(0L);
                    baseChannel.setNoticeVisitDays(0L);
                    baseChannel.setNoticeSignDays(0L);
                    baseChannel.setNoticeLoanDays(0L);
                    baseChannel.setCityLimit(city);
                    baseChannel.setApplyLimit(0L);
                    baseChannel.setAgeLimit(0L);
                    baseChannel.setRejectDays(9999L);
                    baseChannel.setStatus(8L);
                    baseChannel.setDetailsDisplay(1L);
                    baseChannel.setCreateTime(new Date());
                    baseChannel.setOpenFlag(1L);
                    iBaseChannelService.insertBaseChannel(baseChannel);
                }
                setCode(0);
                setMsg("success");
            } else {
                setCode(-2);
                setMsg("渠道已存在");
            }

            logger.info("同步新增渠道{}", channel_source);
        } catch (Exception e) {
            logger.error("渠道同步异常", e);
            setCode(-1);
            setMsg("渠道同步异常");
            return JSON.toJSONString(getResult());
        }
        return JSON.toJSONString(getResult());
    }

    /*****************************************报表系统数据同步********************************************/
    /**
     * 机构部门查询-全量
     *
     * @return
     */
    public String syncCompanyOrganization() {
        try {
            list = new ArrayList<>();
            long begin = System.currentTimeMillis();
            String requestBoday = getRequestBoday();
            JSONObject json = JSONObject.parseObject(requestBoday);
            if (json == null) {
                setCode(-1);
                setMsg("请求包数据为空");
                return JSON.toJSONString(getResult());
            }
            logger.info("机构部门查询请求:{}", json.toString());
            // 验证身份能解密就放行
            String token = json.getString("token");
            if (StringUtils.isBlank(token)) {
                setCode(-1);
                setMsg("无权限访问");
                return JSON.toJSONString(getResult());
            }
            String realVal = AesUtils.decrypt(token, baseSysConfigService.getItemValueByItemKey(ConfigConstant.DATA_CENTER_AES_KEY));
            if (StringUtils.isBlank(realVal)) {
                setCode(-1);
                setMsg("无权限访问");
                return JSON.toJSONString(getResult());
            }
            Map<String, Object> params = new HashMap<>();
            params.put("reportType", 1001);
            setList(custInfoService.commonStatics(params));
            setCode(0);
            setMsg("success");
            long end = System.currentTimeMillis();
            logger.info("机构部门查询结果集数量：{}, 耗时{}ms", list.size(), (end - begin));
        } catch (Exception e) {
            logger.error("机构部门查询异常", e);
            setCode(-1);
            setMsg("机构部门查询异常");
            return JSON.toJSONString(getResult());
        }
        return JSON.toJSONString(getResult());
    }

    /**
     * 机构用户查询-全量
     *
     * @return
     */
    public String syncCompanyUser() {
        try {
            list = new ArrayList<>();
            long begin = System.currentTimeMillis();
            String requestBoday = getRequestBoday();
            JSONObject json = JSONObject.parseObject(requestBoday);
            if (json == null) {
                setCode(-1);
                setMsg("请求包数据为空");
                return JSON.toJSONString(getResult());
            }
            logger.info("机构用户查询请求:{}", json.toString());
            // 验证身份能解密就放行
            String token = json.getString("token");
            if (StringUtils.isBlank(token)) {
                setCode(-1);
                setMsg("无权限访问");
                return JSON.toJSONString(getResult());
            }
            String realVal = AesUtils.decrypt(token, baseSysConfigService.getItemValueByItemKey(ConfigConstant.DATA_CENTER_AES_KEY));
            if (StringUtils.isBlank(realVal)) {
                setCode(-1);
                setMsg("无权限访问");
                return JSON.toJSONString(getResult());
            }
            Map<String, Object> params = new HashMap<>();
            params.put("reportType", 1002);
            setList(custInfoService.commonStatics(params));
            setCode(0);
            setMsg("success");
            long end = System.currentTimeMillis();
            logger.info("机构用户结果集数量：{}, 耗时{}ms", list.size(), (end - begin));
        } catch (Exception e) {
            logger.error("机构用户查询异常", e);
            setCode(-1);
            setMsg("机构用户查询异常");
            return JSON.toJSONString(getResult());
        }
        return JSON.toJSONString(getResult());
    }

    /**
     * 机构客户查询
     *
     * @return
     */
    public String syncCompanyCustInfo() {
        try {
            long begin = System.currentTimeMillis();
            String requestBoday = getRequestBoday();
            JSONObject json = JSONObject.parseObject(requestBoday);
            if (json == null) {
                setCode(-1);
                setMsg("请求包数据为空");
                return JSON.toJSONString(getResult());
            }
            logger.info("机构线索查询请求:{}", json.toString());
            // 验证身份能解密就放行
            String token = json.getString("token");
            if (StringUtils.isBlank(token)) {
                setCode(-1);
                setMsg("无权限访问");
                return JSON.toJSONString(getResult());
            }
            String realVal = AesUtils.decrypt(token, baseSysConfigService.getItemValueByItemKey(ConfigConstant.DATA_CENTER_AES_KEY));
            if (StringUtils.isBlank(realVal)) {
                setCode(-1);
                setMsg("无权限访问");
                return JSON.toJSONString(getResult());
            }
            // 开始时间
            String start_time = StringUtils.defaultIfBlank(json.getString("start_time"), "");
            if (StringUtils.isBlank(start_time)) {
                setCode(-1);
                setMsg("查询开始时间为空");
                return JSON.toJSONString(getResult());
            }
            Map<String, Object> params = new HashMap<>();
            params.put("reportType", 1003);
            params.put("start_time", start_time);
            setList(custInfoService.commonStatics(params));
            setCode(0);
            long end = System.currentTimeMillis();
            logger.info("机构线索查询{}，结果集数量：{}, 耗时{}ms", start_time, list.size(), (end - begin));
        } catch (Exception e) {
            logger.error("机构线索查询异常", e);
            setCode(-1);
            setMsg("机构线索查询异常");
            return JSON.toJSONString(getResult());
        }
        return JSON.toJSONString(getResult());
    }

    /**
     * 机构来访登记查询
     *
     * @return
     */
    public String syncCompanyCustVisitInfo() {
        try {
            long begin = System.currentTimeMillis();
            String requestBoday = getRequestBoday();
            JSONObject json = JSONObject.parseObject(requestBoday);
            if (json == null) {
                setCode(-1);
                setMsg("请求包数据为空");
                return JSON.toJSONString(getResult());
            }
            logger.info("机构来访登记查询请求:{}", json.toString());
            // 验证身份能解密就放行
            String token = json.getString("token");
            if (StringUtils.isBlank(token)) {
                setCode(-1);
                setMsg("无权限访问");
                return JSON.toJSONString(getResult());
            }
            String realVal = AesUtils.decrypt(token, baseSysConfigService.getItemValueByItemKey(ConfigConstant.DATA_CENTER_AES_KEY));
            if (StringUtils.isBlank(realVal)) {
                setCode(-1);
                setMsg("无权限访问");
                return JSON.toJSONString(getResult());
            }
            // 开始时间
            String start_time = StringUtils.defaultIfBlank(json.getString("start_time"), "");
            if (StringUtils.isBlank(start_time)) {
                setCode(-1);
                setMsg("查询开始时间为空");
                return JSON.toJSONString(getResult());
            }
            Map<String, Object> params = new HashMap<>();
            params.put("reportType", 1004);
            params.put("start_time", start_time);
            setList(custInfoService.commonStatics(params));
            setCode(0);
            long end = System.currentTimeMillis();
            logger.info("机构来访登记查询{}，结果集数量：{}, 耗时{}ms", start_time, list.size(), (end - begin));
        } catch (Exception e) {
            logger.error("机构来访登记查询异常", e);
            setCode(-1);
            setMsg("机构来访登记查询异常");
            return JSON.toJSONString(getResult());
        }
        return JSON.toJSONString(getResult());
    }

    /**
     * 机构进件查询
     *
     * @return
     */
    public String syncCompanyIncomingInfo() {
        try {
            long begin = System.currentTimeMillis();
            String requestBoday = getRequestBoday();
            JSONObject json = JSONObject.parseObject(requestBoday);
            if (json == null) {
                setCode(-1);
                setMsg("请求包数据为空");
                return JSON.toJSONString(getResult());
            }
            logger.info("机构进件查询请求:{}", json.toString());
            // 验证身份能解密就放行
            String token = json.getString("token");
            if (StringUtils.isBlank(token)) {
                setCode(-1);
                setMsg("无权限访问");
                return JSON.toJSONString(getResult());
            }
            String realVal = AesUtils.decrypt(token, baseSysConfigService.getItemValueByItemKey(ConfigConstant.DATA_CENTER_AES_KEY));
            if (StringUtils.isBlank(realVal)) {
                setCode(-1);
                setMsg("无权限访问");
                return JSON.toJSONString(getResult());
            }
            // 开始时间
            String start_time = StringUtils.defaultIfBlank(json.getString("start_time"), "");
            if (StringUtils.isBlank(start_time)) {
                setCode(-1);
                setMsg("查询开始时间为空");
                return JSON.toJSONString(getResult());
            }
            Map<String, Object> params = new HashMap<>();
            params.put("reportType", 1005);
            params.put("start_time", start_time);
            setList(custInfoService.commonStatics(params));
            setCode(0);
            long end = System.currentTimeMillis();
            logger.info("机构进件查询{}，结果集数量：{}, 耗时{}ms", start_time, list.size(), (end - begin));
        } catch (Exception e) {
            logger.error("机构进件查询异常", e);
            setCode(-1);
            setMsg("机构进件查询异常");
            return JSON.toJSONString(getResult());
        }
        return JSON.toJSONString(getResult());
    }

    /**
     * 机构客户跟进记录查询
     *
     * @return
     */
    public String syncCompanyCustFollow() {
        try {
            long begin = System.currentTimeMillis();
            String requestBoday = getRequestBoday();
            JSONObject json = JSONObject.parseObject(requestBoday);
            if (json == null) {
                setCode(-1);
                setMsg("请求包数据为空");
                return JSON.toJSONString(getResult());
            }
            logger.info("机构客户跟进记录查询请求:{}", json.toString());
            // 验证身份能解密就放行
            String token = json.getString("token");
            if (StringUtils.isBlank(token)) {
                setCode(-1);
                setMsg("无权限访问");
                return JSON.toJSONString(getResult());
            }
            String realVal = AesUtils.decrypt(token, baseSysConfigService.getItemValueByItemKey(ConfigConstant.DATA_CENTER_AES_KEY));
            if (StringUtils.isBlank(realVal)) {
                setCode(-1);
                setMsg("无权限访问");
                return JSON.toJSONString(getResult());
            }
            // 开始时间
            String start_time = StringUtils.defaultIfBlank(json.getString("start_time"), "");
            if (StringUtils.isBlank(start_time)) {
                setCode(-1);
                setMsg("查询开始时间为空");
                return JSON.toJSONString(getResult());
            }
            Map<String, Object> params = new HashMap<>();
            params.put("reportType", 1006);
            params.put("start_time", start_time);
            setList(custInfoService.commonStatics(params));
            setCode(0);
            long end = System.currentTimeMillis();
            logger.info("机构客户跟进记录查询{}，结果集数量：{}, 耗时{}ms", start_time, list.size(), (end - begin));
        } catch (Exception e) {
            logger.error("机构客户跟进记录查询异常", e);
            setCode(-1);
            setMsg("机构客户跟进记录查询异常");
            return JSON.toJSONString(getResult());
        }
        return JSON.toJSONString(getResult());
    }

    /**
     * 机构删除线索查询
     *
     * @return
     */
    public String syncCompanyCustDel() {
        try {
            long begin = System.currentTimeMillis();
            String requestBoday = getRequestBoday();
            JSONObject json = JSONObject.parseObject(requestBoday);
            if (json == null) {
                setCode(-1);
                setMsg("请求包数据为空");
                return JSON.toJSONString(getResult());
            }
            logger.info("机构删除线索查询请求:{}", json.toString());
            // 验证身份能解密就放行
            String token = json.getString("token");
            if (StringUtils.isBlank(token)) {
                setCode(-1);
                setMsg("无权限访问");
                return JSON.toJSONString(getResult());
            }
            String realVal = AesUtils.decrypt(token, baseSysConfigService.getItemValueByItemKey(ConfigConstant.DATA_CENTER_AES_KEY));
            if (StringUtils.isBlank(realVal)) {
                setCode(-1);
                setMsg("无权限访问");
                return JSON.toJSONString(getResult());
            }
            // 开始时间
            String start_time = StringUtils.defaultIfBlank(json.getString("start_time"), "");
            Map<String, Object> params = new HashMap<>();
            params.put("reportType", 1007);
            params.put("update_time", start_time);
            setList(custInfoService.commonStatics(params));
            setCode(0);
            long end = System.currentTimeMillis();
            logger.info("机构删除线索查询{}，结果集数量：{}, 耗时{}ms", start_time, list.size(), (end - begin));
        } catch (Exception e) {
            logger.error("机构删除线索查询异常", e);
            setCode(-1);
            setMsg("机构删除线索查询异常");
            return JSON.toJSONString(getResult());
        }
        return JSON.toJSONString(getResult());
    }

    /**
     * 获取post的请求参数
     *
     * @return
     */
    public String getRequestBoday() {
        HttpServletRequest request = (HttpServletRequest) ServletUtils.getRequest();
        InputStream inputStream;
        String strResponse = "";
        try {
            inputStream = request.getInputStream();
            String strMessage = "";
            BufferedReader reader;
            reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
            while ((strMessage = reader.readLine()) != null) {
                strResponse += strMessage;
            }
            reader.close();
            inputStream.close();
        } catch (IOException e) {

        }
        return strResponse;
    }
}
